#!/bin/bash

# 交付管理系统部署脚本
# 用于自动化部署 Next.js 应用到生产环境

set -e  # 遇到错误立即退出

# 配置变量
PROJECT_NAME="delivery-management"
PROJECT_PATH="/var/www/$PROJECT_NAME"
NGINX_CONFIG_PATH="/etc/nginx/sites-available/$PROJECT_NAME"
NGINX_ENABLED_PATH="/etc/nginx/sites-enabled/$PROJECT_NAME"
SERVICE_NAME="delivery-management"
NODE_PORT=3001

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为 root 用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要 root 权限运行"
        exit 1
    fi
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查 Node.js
    if ! command -v node &> /dev/null; then
        log_error "Node.js 未安装，请先安装 Node.js"
        exit 1
    fi
    
    # 检查 npm
    if ! command -v npm &> /dev/null; then
        log_error "npm 未安装，请先安装 npm"
        exit 1
    fi
    
    # 检查 nginx
    if ! command -v nginx &> /dev/null; then
        log_error "nginx 未安装，请先安装 nginx"
        exit 1
    fi
    
    log_info "依赖检查完成"
}

# 创建项目目录
setup_project_directory() {
    log_info "设置项目目录..."
    
    # 创建项目目录
    mkdir -p $PROJECT_PATH
    
    # 复制项目文件
    log_info "复制项目文件到 $PROJECT_PATH"
    cp -r ./* $PROJECT_PATH/
    
    # 设置权限
    chown -R www-data:www-data $PROJECT_PATH
    chmod -R 755 $PROJECT_PATH
    
    # 保护敏感文件
    chmod 600 $PROJECT_PATH/data/*.db* 2>/dev/null || true
    
    log_info "项目目录设置完成"
}

# 安装依赖并构建
build_project() {
    log_info "安装依赖并构建项目..."
    
    cd $PROJECT_PATH
    
    # 安装生产依赖
    npm ci --only=production
    
    # 构建项目
    npm run build
    
    log_info "项目构建完成"
}

# 配置 nginx
setup_nginx() {
    log_info "配置 nginx..."
    
    # 复制 nginx 配置
    cp nginx.conf $NGINX_CONFIG_PATH
    
    # 更新配置中的路径
    sed -i "s|/var/www/delivery-management|$PROJECT_PATH|g" $NGINX_CONFIG_PATH
    
    # 启用站点
    ln -sf $NGINX_CONFIG_PATH $NGINX_ENABLED_PATH
    
    # 删除默认站点 (如果存在)
    rm -f /etc/nginx/sites-enabled/default
    
    # 测试 nginx 配置
    nginx -t
    
    # 重启 nginx
    systemctl restart nginx
    systemctl enable nginx
    
    log_info "nginx 配置完成"
}

# 创建 systemd 服务
create_systemd_service() {
    log_info "创建 systemd 服务..."
    
    cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=Delivery Management System
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=$PROJECT_PATH
Environment=NODE_ENV=production
Environment=PORT=$NODE_PORT
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=$SERVICE_NAME

[Install]
WantedBy=multi-user.target
EOF

    # 重新加载 systemd
    systemctl daemon-reload
    
    # 启用并启动服务
    systemctl enable $SERVICE_NAME
    systemctl start $SERVICE_NAME
    
    log_info "systemd 服务创建完成"
}

# 创建 Next.js 服务器启动文件
create_server_file() {
    log_info "创建服务器启动文件..."
    
    cat > $PROJECT_PATH/server.js << 'EOF'
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = process.env.PORT || 3001

const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      const parsedUrl = parse(req.url, true)
      await handle(req, res, parsedUrl)
    } catch (err) {
      console.error('Error occurred handling', req.url, err)
      res.statusCode = 500
      res.end('internal server error')
    }
  }).listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://${hostname}:${port}`)
  })
})
EOF

    chown www-data:www-data $PROJECT_PATH/server.js
    chmod 644 $PROJECT_PATH/server.js
    
    log_info "服务器启动文件创建完成"
}

# 设置防火墙
setup_firewall() {
    log_info "配置防火墙..."
    
    # 检查 ufw 是否安装
    if command -v ufw &> /dev/null; then
        ufw allow 'Nginx Full'
        ufw allow ssh
        log_info "防火墙配置完成"
    else
        log_warn "ufw 未安装，请手动配置防火墙"
    fi
}

# 显示部署状态
show_status() {
    log_info "部署状态检查..."
    
    echo "=== 服务状态 ==="
    systemctl status $SERVICE_NAME --no-pager -l
    
    echo ""
    echo "=== nginx 状态 ==="
    systemctl status nginx --no-pager -l
    
    echo ""
    echo "=== 端口监听状态 ==="
    netstat -tlnp | grep -E ":80|:$NODE_PORT"
    
    echo ""
    log_info "部署完成！"
    log_info "访问地址: http://your-server-ip"
    log_info "管理命令:"
    log_info "  查看应用日志: journalctl -u $SERVICE_NAME -f"
    log_info "  重启应用: systemctl restart $SERVICE_NAME"
    log_info "  重启 nginx: systemctl restart nginx"
}

# 主函数
main() {
    log_info "开始部署交付管理系统..."
    
    check_root
    check_dependencies
    setup_project_directory
    build_project
    create_server_file
    setup_nginx
    create_systemd_service
    setup_firewall
    show_status
    
    log_info "部署完成！"
}

# 执行主函数
main "$@"
